package appapi.service.impl;


import appapi.Global.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service("localStorageService")
public class LocalStorageService {

    @Value("${web.upload-path}")
    private String uploadDir;
    @Value("${web.image-path}")
    private String visitPath;

    private static final String[] ALLOW_FILE_TYPES = { "jpg","jpeg","png","docx","xlsx","pdf","xls","apk"};

    public String upload(Integer type, MultipartFile file) throws Exception {
        //此处判断后缀
        String contentType =  file.getOriginalFilename().toLowerCase();
        boolean allowType = false;
        for (String allowFileType : ALLOW_FILE_TYPES) {
            if(contentType.endsWith(allowFileType)) {
                allowType = true;
                break;
            }
        }

        if (!allowType) {
           throw new BusinessException(400,"请上传正确的文件格式!");
        }
        String fileId = UUID.randomUUID().toString();
        //String subFolder = hashBy256(fileId);
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        String subFolder = "base"+ formatter.format(date);
        //传图片
        if(type==1)
        {
            subFolder = "rec"+formatter.format(date);
        }
        File destFolder = new File(uploadDir + File.separator + subFolder);
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        String originalFilename = file.getOriginalFilename();
        String fileExt = getFileType(originalFilename);
        String destFileName = fileId + "--" + originalFilename;
        File destFile = new File(uploadDir + File.separator + subFolder +  File.separator + destFileName);
        log.info("file saved in: {}", destFile.getAbsoluteFile());
        file.transferTo(destFile);

        //String filePath = visitPath + File.separator + subFolder + File.separator + destFileName;

        String filePath = File.separator + subFolder + File.separator + destFileName;
        String fileUri = visitPath.concat(transferPathAsImageUri(filePath));

        Long fileSize = file.getSize();

        //存入数据库(未使用)
//        SysFile sysFile = SysFile.builder()
//                .fileId(fileId)
//                .filePath(filePath)
//                .fileFormat(fileExt)
//                .fileSize(fileSize)
//                .mediaType(contentType)
//                .originalName(originalFilename)
//                .build();
        //SysFile.save(sysFile);

        return fileUri;
    }

    private String getFileType(String originalFilename){
        int extPos = originalFilename.lastIndexOf(".");
        if (extPos != -1) {
            return originalFilename.substring(extPos + 1);
        }
        throw new RuntimeException("未知类型");
    }

    public static String hashBy256(String str) {
        String s = Integer.toHexString(Math.abs(str.hashCode()) % 256).toUpperCase();
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    public static String transferPathAsImageUri(String fileServerPath) {
        if (!StringUtils.hasLength(fileServerPath)) {
            return null;
        }
        return fileServerPath.replaceAll("\\\\", "/");
    }
}
